package com.example.wordlistdemo;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class WordListConfigDatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "word_list_config.db";
    private static final int DATABASE_VERSION = 1;

    private static final String TABLE_NAME = "word_list_config";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_CODE = "code";
    private static final String COLUMN_CODE_VALUE = "code_value";

    // 创建表的 SQL 语句
    private static final String CREATE_TABLE_QUERY =
            "CREATE TABLE " + TABLE_NAME + " (" +
                    COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    COLUMN_CODE + " TEXT UNIQUE, " +
                    COLUMN_CODE_VALUE + " TEXT);";

    public WordListConfigDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_QUERY);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 如果需要升级数据库，可以在这里处理
    }


    public long saveConfig(String code, String codeValue) {
        SQLiteDatabase db = this.getWritableDatabase();
        // 使用 insertWithOnConflict 方法，指定冲突处理策略为 REPLACE
        ContentValues values = new ContentValues();
        values.put(COLUMN_CODE, code);
        values.put(COLUMN_CODE_VALUE, codeValue);
        long id = db.insertWithOnConflict(TABLE_NAME, null, values, SQLiteDatabase.CONFLICT_REPLACE);
        db.close();
        return id;
    }

    // 查询配置的方法（示例，你可以根据需求自行修改）
    @SuppressLint("Range")
    public WordListConfig getConfig(String code) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME, null, COLUMN_CODE + " = ?", new String[]{code}, null, null, null);
        WordListConfig config = null;
        if (cursor != null && cursor.moveToFirst()) {
            config = new WordListConfig();
            config.setId(cursor.getLong(cursor.getColumnIndex(COLUMN_ID)));
            config.setCode(cursor.getString(cursor.getColumnIndex(COLUMN_CODE)));
            config.setCodeValue(cursor.getString(cursor.getColumnIndex(COLUMN_CODE_VALUE)));
        }
        if (cursor != null) {
            cursor.close();
        }
        db.close();
        return config;
    }
}

